/**
 * Created by Administrator on 2017/01/19.
 */

import Vue from "vue";
import BigNumber from 'bignumber.js';
import filter from '../../../grsc-base/util/filter';
import mathtool from '../../../grsc-base/util/mathtool';
import commonService from '../../common/commonService';
import Popover from '../../../grsc-base/component/Popover.vue';
import Help from '../../../grsc-base/component/Help.vue';
import Pager from '../../../grsc-base/component/Pager.vue';
import NoData from '../../../grsc-base/component/NoData.vue';
import Loading from '../../../grsc-base/component/Loading.vue';
import Validator from '../../../grsc-base/component/Validator/main';
import format from '../../common/format';
import lib from '../../common/lib';
import tpl from "./tpl.html";
import service from './service';
import PayDialogBuy from './PayDialogBuy';
import PayDialogSell from './PayDialogSell';
import FundTip from './FundTip.vue';

import setPayPwd from '../../component/setPayPwd/main';
import util from './util';

const MAX_SMCFUND_AMOUT = 10000;
export default Vue.extend({
    name: "MarketLimit",
    template: tpl,
    components: {
        Pager,
        NoData,
        Loading,
        Popover,
        Help,
        Validator,
        PayDialogBuy,
        PayDialogSell,
        setPayPwd,
        FundTip
    },
    computed: {
        /**
         * 购买总额
         * @returns {*}
         */
        buyTotal() {
            if ($.isNumeric(this.buyForm.price) === false || $.isNumeric(this.buyForm.amount) === false) {
                return '--';
            }
            let total;
            if (this.$$symbol === 'ACT_AAC') {
                total = new BigNumber(this.buyForm.price).mul(this.buyForm.amount).mul(100000000).floor().div(100000000);
            } else {
                total = filter.floorFix(mathtool.multiplication(this.buyForm.price, this.buyForm.amount,this.$$coinPrecision), this.$$coinPrecision);
            }
            // let total = new BigNumber(this.buyForm.price).mul(this.buyForm.amount).mul(10000).floor().div(10000);
            // debugger;
            // let total = filter.floorFix(mathtool.multiplication(this.buyForm.price, this.buyForm.amount,this.$$coinPrecision), this.$$coinPrecision);
            return format.formatZeroSuffix(total, this.$$coinPrecision);
        },
        /**
         * 卖出总额
         * @returns {*}
         */
        sellTotal() {
            if ($.isNumeric(this.sellForm.price) === false || $.isNumeric(this.sellForm.amount) === false) {
                return '--';
            }
            // let total = new BigNumber(this.sellForm.price).mul(this.sellForm.amount).mul(10000).floor().div(10000);
            let total;
            if (this.$$symbol === 'ACT_AAC') {
                total = new BigNumber(this.sellForm.price).mul(this.sellForm.amount).mul(100000000).floor().div(100000000);
            }else{
                total = filter.floorFix(mathtool.multiplication(this.sellForm.price, this.sellForm.amount,this.$$coinPrecision), this.$$coinPrecision);
            }
            // let total = filter.floorFix(mathtool.multiplication(this.sellForm.price, this.sellForm.amount,this.$$coinPrecision), this.$$coinPrecision);
            return format.formatZeroSuffix(total, this.$$coinPrecision);
        }

    },
    data() {
        return {
            // 买1
            firstBuyPrice: 0,
            firstSellPrice: 0,

            coinBalance: '--.--',
            currencyBalance: '--.--',
            coinBalanceLock:0,
            hasAuthLevel2: false,
            buyForm: {
                'price': '',
                'amount': '',
                'tradeCoinType':'BUY',
                'tradeCoinFlag':'FIXED'

            },
            sellForm: {
                'price': '',
                'amount': '',
                'tradeCoinType':'SELL',
                'tradeCoinFlag':'FIXED'
            },
            buyPercent: '',
            sellPercent: '',
            isShowPayDialogBuy: false,
            isShowPayDialogSell: false,
            isShowFundTip:false,
            isShowSetPayPwd: false,     //设置密码modal 2017/12/15 lanyunlong
            isSetPayPassword: false,
            isBuy: true,


            isRequesting: false,

            changeUnit:0.0001 ,//手动更改价格增长幅度
            symbolStatus:'INIT', //INIT （PRELISTED） LISTED DELISTED
            ticketStatus:'',//UNPURCHASED  PURCHASED  RETURNED
            fundTipType:'TICKET'
        };
    },
    created() {
        this._fetchTotalAssets();
        this._fetchSymbolRules();
        this._initChangeUnit();

        this._doAuth();

        $(document).off('$$market.SetPrice').on('$$market.SetPrice', (event, price, amount) => {
            this.setPrice(price, +amount);
        });
    },
    mounted() {
        window.setTimeout(() => {
            this.buyForm.price = '';
            this.buyForm.amount = '';
            this.sellForm.price = '';
            this.sellForm.amount = '';
        }, 0);

        this.fetchPayPsdStatus();
    },

    methods: {

        /**
         * 判断用户是否经过实名认证
         * @private
         */
        _doAuth() {
            let accountNo = lib.getAccountNo();
            let hasAuth2 = window.localStorage.getItem('HAS_AUTH_' + accountNo);
            // 如果是null，说明没有请求过该用户的基本信息
            if (hasAuth2 === null) {
                commonService.basic().done((rep) => {
                    this.hasAuthLevel2 = lib.hasAuthLevel2();
                });
            } else if (hasAuth2 === '2') {
                this.hasAuthLevel2 = true;
            } else if (hasAuth2 === '1') {
                this.hasAuthLevel2 = false;
            }
        },


        _fetchSymbolRules(){
            service.symbol({
                'symbolName':this.$$symbol
            }).done((rep)=>{
                if(rep.code === window.CODE.SUCCESS){
                    this.symbolStatus = rep.data.status;
                    //对smcf1单独处理  USDT_SMCF1
                    if(this.symbolStatus === 'LISTED' && this.$$symbol === 'USDT_SMCF1'){
                        this.queryFundSymbol(this.$$symbol.split('_')[1] , this.$$symbol);
                    }
                }
            })
        },

        _initChangeUnit(){
            if(this.$$coinPrecision<4){
                this.changeUnit = mathtool.division(1,Math.pow(10,this.$$coinPrecision));
            }
        },

        /**
         * 设置买入百分比
         * @param percent
         */
        setBuyPercent(percent) {
            if (this.buyForm.price === '') {
                this.buyForm.price = this.firstBuyPrice;
                this.buyRules.price.$setRight('');
                this.buyRules.price.$setHighlight();
            }
            this.buyForm.amount = util.getMaxCoin(this.currencyBalance, this.buyForm.price, percent);
            this.buyRules.amount.$setRight();
            this.buyRules.amount.$setHighlight();

            setTimeout(() => {
                this.buyPercent = percent;
            }, 10);
        },

        /**
         * 设置卖出百分比
         * @param percent
         */
        setSellPercent(percent) {
            if (this.sellForm.price === '') {
                this.sellForm.price = this.firstSellPrice;
                this.sellRules.price.$setRight('');
                this.sellRules.price.$setHighlight();
            }
            this.sellForm.amount = filter.floorFix(mathtool.division(this.coinBalance, percent));
            this.sellRules.amount.$setRight();

            // 设置高亮
            this.sellRules.amount.$setHighlight();

            // 这里用10毫秒, 是为了确保watch -> buyForm.amount的内容先去执行
            setTimeout(() => {
                this.sellPercent = percent;
            }, 10);
        },

        /**
         * 买卖盘点击
         * @param price
         * @param number
         */
        setPrice(price, amount) {

            this.buyForm.price = price;
            this.buyRules.price.$setRight('');
            this.buyRules.price.$setHighlight();
            // 重置比例
            this.buyPercent = '';
            console.log('The price is ' + price);
            this.sellForm.price = price;
            this.sellRules.price.$setRight('');
            this.sellRules.price.$setHighlight();
        },

        /**
         * 设置买1和卖1价
         * @param buy1
         * @param sell1
         */
        setFirstPrice(buy1, sell1) {
            this.firstBuyPrice = sell1;
            this.firstSellPrice = buy1;

            // 添加默认值
            this.buyForm.price = sell1;
            this.sellForm.price = buy1;
        },

        fetchPayPsdStatus(){
            commonService.basic().done(rep=>{
                if(rep.code === window.CODE.SUCCESS){
                    this.isSetPayPassword = rep.data.setPayPassword;
                }else {
                    window.toast(rep.msg);
                }
            })
        },

        /**
         * 买入
         */
        buy() {
            this.isBuy = true;
            if (this.buyRules.$checkAll() === false) {
                return;
            }
            /***** 于此处请求判断是否存在交易密码 2017-12-15 lanyunlong *****/
            if(this.$$symbol === 'USDT_SMCF1' && this._checkFundStatus('BUY') === false){

            }else if(this.isSetPayPassword === false){
                this.isShowSetPayPwd = true;
            }else{
                this.isShowPayDialogBuy = true;
            }
        },

        /**
         * 卖出
         */
        sell() {
            this.isBuy = false;
            if (this.sellRules.$checkAll() === false) {
                return;
            }
            /***** 于此处请求判断是否存在交易密码 2017-12-15 lanyunlong *****/
            if(this.$$symbol === 'USDT_SMCF1' && this._checkFundStatus() === false){

            }else if(this.isSetPayPassword === false){
                this.isShowSetPayPwd = true;
            }else{
                this.isShowPayDialogSell = true;
            }
        },


        /**
         * 点击购买时判断当前用户购买资格
         * */
        _checkFundStatus(type){
            //只有预售阶段，判断是不是有票
            if(this.symbolStatus === 'PRELISTED' && this.ticketStatus === 'UNPURCHASED'){
                this.isShowFundTip = true;
                return false;
            }else if(!lib.hasAuth() && type === 'BUY'){
                //如果当前用户没有实名认证 总额不得超过1万
                let sum = mathtool.add(mathtool.add(this.coinBalance,this.coinBalanceLock), this.buyForm.amount);
                if(sum >= MAX_SMCFUND_AMOUT){
                    this.isShowFundTip = true;
                    this.fundTipType = 'AUTH';
                    return false;
                }
            }
        },



        onSetPayPwdSuccess() {
            this.isSetPayPassword = true;
            if(this.isBuy){
                this.isShowPayDialogBuy = true;
            }else{
                this.isShowPayDialogSell = true;
            }
        },

        hidePayDialogBuy() {
            this.isShowPayDialogBuy = false;
        },

        hidePayDialogSell() {
            this.isShowPayDialogSell = false;
        },
        hidSetPayPwd() {
            this.isShowSetPayPwd = false;

        },

        resetBuyForm() {
            this.buyForm.price = '';
            this.buyForm.amount = '';
        },

        resetSellForm() {
            this.sellForm.price = '';
            this.sellForm.amount = '';
        },

        /**
         * 购买成功回调
         */
        onBuySuccess() {
            this.hidePayDialogBuy();
            this.resetBuyForm();
            this._fetchTotalAssets();
        },

        /**
         * 卖出成功回调
         */
        onSellSuccess() {
            this.hidePayDialogSell();
            this.resetSellForm();
            this._fetchTotalAssets();
        },

        /**
         * 买, 价格涨
         */
        setBuyPriceUp() {
            if (this.buyForm.price !== '') {
                this.buyForm.price = mathtool.add(+this.buyForm.price, this.changeUnit, this.$$coinPrecision);
                this.buyRules.price.$check();
            }
        },

        /**
         * 买, 价格降
         */
        setBuyPriceDown() {
            if (this.buyForm.price !== '') {
                this.buyForm.price = mathtool.reduce(+this.buyForm.price, this.changeUnit, this.$$coinPrecision);
                this.buyRules.price.$check();
            }
        },

        /**
         * 卖, 价格涨
         */
        setSellPriceUp() {
            if (this.sellForm.price !== '') {
                this.sellForm.price = mathtool.add(+this.sellForm.price, this.changeUnit, this.$$coinPrecision);
                this.sellRules.price.$check();
            }
        },

        /**
         * 卖, 价格降
         */
        setSellPriceDown() {
            if (this.sellForm.price !== '') {
                this.sellForm.price = mathtool.reduce(+this.sellForm.price, this.changeUnit, this.$$coinPrecision);
                this.sellRules.price.$check();
            }
        },

        /**
         * 登录
         */
        gologin() {
            window.location.href = './login.html';
        },

        /**
         * 查询当前基金交易对能够购买
         * */
        queryFundSymbol(fundAssetCode,fundSymbol){

            let param = {
                fundAssetCode,
                fundSymbol
            };
            service.queryFundSymbol(param).done(rep=>{
                if(rep.code === window.CODE.SUCCESS){
                    this.symbolStatus = rep.data.symbolStatus;
                    this.ticketStatus = rep.data.ticketStatus;

                }
            }).always(()=>{

            })
        }

    }
})
